<?php
class Karyawan_history_jabatan_model extends MY_Model {
	
    function Karyawan_history_jabatan_model(){
        parent::MY_Model();
        $this->load->database();
        $this->table_name = "karyawan_history_jabatan";
    }
    
    /**
     * 
     * @param $id
     */
    function select_by_id($id){
    	return $query = $this->db->get_where($this->table_name, array('kary_jbt_id' => $id));
    }
    
    function getActive($kary_id){
    	$now = date("Y-m-d",time());
    	return $this->getHistory($kary_id, false, "'$now' BETWEEN a.kary_jbt_tgl_menjabat AND a.kary_jbt_tgl_berhenti",10,0,"jbt_nama ASC, dep_nama ASC");
    }
    
	function getHistory($kary_id, $key=false, $where=false, $limit=10, $offset=0, $orderby=false){
 		/**
 		 * THE SQL:
 		 * 		SELECT a.*, b.kary_nama, c.jbt_nama 
 		 * 		FROM `karyawan_history_jabatan` as a, karyawan as b, jabatan as c, d.departemen
 		 * 		WHERE a.kary_id = b.kary_id and a.jbt_id = c.jbt_id
 		 */
 		if ($key){
 			$key = "AND (
			  a.`kary_jbt_id` LIKE '%$key%' OR
			  a.`kary_jbt_tgl_menjabat` LIKE '%$key%' OR
			  a.`kary_jbt_tgl_berhenti` LIKE '%$key%' OR
			  a.`kary_id` LIKE '%$key%' OR
			  a.`jbt_id` LIKE '%$key%')";
 		}
 		
 		if ($where) { 
 			if (is_array($where)){
 				$oo = "";
 				foreach(array_keys($where) as $rr){
 					$oo .= ($oo? " AND " : ""). "$rr ".$where[$rr];
 				}
 				$where = "$oo ";
 			}else{
 				$where = " AND $where";
 			}
 		}
 	
 		if ($orderby){ 
 			if (is_array($orderby)){
 				$oo = "";
 				foreach(array_keys($orderby) as $rr){
 					$oo .= ($oo? "," : ""). "$rr ".$orderby[$rr];
 				}
 				$orderby = "ORDER BY $oo ";
 			}else{
 				$orderby = "ORDER BY $orderby";
 			} 
 		}
 		
 		$limit = " LIMIT $offset,$limit ";  
 		
    	return $this->db->query(
    		"SELECT a.*, b.kary_nama, c.jbt_nama, d.dep_nama
 		  	FROM `karyawan_history_jabatan` as a, `karyawan` as b, `jabatan` as c, `departemen` as d
 		  	WHERE a.kary_id = b.kary_id 
 		  		AND a.jbt_id = c.jbt_id 
 		  		AND a.kary_id='$kary_id'
 		  		AND c.dep_id = d.dep_id
 		  		$key 
 		  		$where
 		  		$orderby 
 		  		$limit");
    }
}